package com.wmm.jinhong;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import com.common.util.SPUtils;
import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import cz.msebera.android.httpclient.Header;

public class MainActivity extends AppCompatActivity {
    static final String TAG = "ScannerApiTest";
    @BindView(R.id.txt_number)
    TextView txtNumber;
    Intent intent;
    Timer timer=null;
    private List<Bean> list=new ArrayList<>();
    private boolean cancle=true;
    TimerTask task;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        intent = new Intent(this, ScannerService.class);
        startService(intent);
        // 程序打开的时候调用服务，只用调用一次即可，不需要在每个activity中都调用
        txtNumber.setText("当前工号: "+SPUtils.get(this,"UserName","").toString());
        init();
        findViewById(R.id.exit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this,LoginActivity.class));
                finish();
            }
        });
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(0);
            }
        };
        timer.schedule(task,0,60000);
    }
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what==1){
//                timer = new Timer();
//                task = new TimerTask() {
//                    @Override
//                    public void run() {
//                        getLists();
//                    }
//                };
//                timer.schedule(task,0,60000);
//                cancle=true;
//                getLists();
            }else{
                getLists();
            }
            super.handleMessage(msg);
        }
    };
    @Override
    public void onBackPressed() {
        moveTaskToBack(false);
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_HOME){
            Intent mIntent = new Intent();
            mIntent.setAction(Intent.ACTION_MAIN);
            mIntent.addCategory(Intent.CATEGORY_HOME);
            startActivity(mIntent);
        }
        return super.onKeyDown(keyCode, event);
    }
    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }
    void init() {
    }
    private void getLists(){
        Cursor cursor = MyApp.getInstance().query(SQLiteDbHelper.TABLE_STUDENT, null,
                "", null,
                null, null, null, null);

        // 不断移动光标获取值
        list.clear();
        while (cursor.moveToNext()) {
            // 直接通过索引获取字段值
            Bean bean=new Bean();
            bean.type=cursor.getString(0);
            bean.time=cursor.getString(2);
            bean.list=cursor.getString(1);
            bean.kehu=cursor.getString(4);
            bean.ydhao=cursor.getString(3);
            list.add(bean);
//            String stuName = cursor.getString(cursor.getColumnIndex("name"));
        }
        cursor.close();
        if(list.size()>0){
            //开始自动提交任务
//            timer.cancel();
//            cancle=false;
//            timer=null;
            Bean bean=list.get(0);
            final List<GangPingBean> gangPingBeanList=new ArrayList<>();
            try {
                JSONArray jsonArray=new JSONArray(bean.list);
                if(jsonArray!=null){
                    for (int i=0;i<jsonArray.length();i++){
                        gangPingBeanList.add(new Gson().fromJson(jsonArray.getJSONObject(i).toString(),GangPingBean.class));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if(gangPingBeanList.size()<0)
                return;
            switch (bean.type) {
                case "1":
                    firstSubmit(gangPingBeanList, bean.time);
                    break;
                case "2":
                    scck(gangPingBeanList, bean.ydhao,  bean.time);
                    break;
                case "3":
                    hcqr(gangPingBeanList, bean.ydhao, bean.time);
                    break;
                case "4":
                    kpcg(gangPingBeanList, bean.ydhao, bean.time);
                    break;
                case "5":
                    cgrk(gangPingBeanList, bean.ydhao, bean.time);
                    break;
                case "6":
                    ztck(gangPingBeanList, bean.ydhao,  bean.time);
                    break;
                case "7":
                    ztrk(gangPingBeanList,  bean.time);
                    break;
            }

        }
    }
    private void ztrk(List<GangPingBean> list, final String time) {
        JSONArray array = null;
        try {
            array = new JSONArray();
            JSONObject object;
            for (int i = 0; i < list.size(); i++) {
                object = new JSONObject();
                object.put("钢瓶号", list.get(i).getGangPingHao());
                object.put("介质", list.get(i).getInvName());
                object.put("规格", list.get(i).getcInvStd());
                object.put("物料编码", list.get(i).getcInvCode());
                object.put("充前重量", "");
                object.put("充后重量", "");
                array.put(object);
            }
            RequestParams requestParams = new RequestParams();
            requestParams.put("sJson", array.toString().replace("=", ":"));
            requestParams.put("sType", 8);
            requestParams.put("sStorageScanID", SPUtils.get(this, "UserName", "").toString());
            requestParams.put("sSyu", SPUtils.get(this, "YuInfo", "").toString());
            requestParams.put("isFull", 1);
            requestParams.put("yunDanHao", "");
            HttpUtils.post(Constant.SCRKURL, requestParams, new TextHttpResponseHandler() {
                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                }
                @Override
                public void onStart() {
                    super.onStart();
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                   handler.sendEmptyMessage(1);
                }
                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    if (responseString.contains("true")) {
                        MyApp.getInstance().delete(SQLiteDbHelper.TABLE_STUDENT,
                                "time = ?", new String[]{time});
                    } else {
                    }
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    private void ztck(List<GangPingBean> list,String ydhao , final String time){
        JSONArray array=null;
        try {
            array=new JSONArray();
            JSONObject object;
            for(int i=0;i<list.size();i++){
                object=new JSONObject();
                object.put("钢瓶号",list.get(i).getGangPingHao());
                object.put("介质",list.get(i).getInvName());
                object.put("规格",list.get(i).getcInvStd());
                object.put("物料编码",list.get(i).getcInvCode());
                object.put("充前重量","");
                object.put("充后重量","");
                array.put(object);
            }
            RequestParams requestParams=new RequestParams();
            requestParams.put("sJson",array.toString().replace("=",":"));
            requestParams.put("sFaYunDanHao",ydhao);
            requestParams.put("sStorageScanID",SPUtils.get(this,"UserName","").toString());
            requestParams.put("sSyu",SPUtils.get(this,"YuInfo","").toString());
            requestParams.put("sType",8);
            requestParams.put("sTiSongHuoDanHao","");
            HttpUtils.post(Constant.KPCGURL, requestParams, new TextHttpResponseHandler() {
                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                }

                @Override
                public void onStart() {
                    super.onStart();
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    handler.sendEmptyMessage(1);
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    if(responseString.contains("true")){
                        MyApp.getInstance().delete(SQLiteDbHelper.TABLE_STUDENT,
                                "time = ?", new String[]{time});
                    }else{
                    }
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    private void cgrk(List<GangPingBean> list,String ydhao, final String time){
        JSONArray array=null;
        try {
            array=new JSONArray();
            JSONObject object;
            for(int i=0;i<list.size();i++){
                object=new JSONObject();
                object.put("gangpinghao",list.get(i).getGangPingHao());
                object.put("isfull",list.get(i).getIsFull());
                object.put("backConfirm",list.get(i).getBackConfirm());
                array.put(object);
            }
            RequestParams requestParams=new RequestParams();
            requestParams.put("sJson",array.toString().replace("=",":"));
            requestParams.put("yunDanHao",ydhao);
            requestParams.put("sStorageScanID",SPUtils.get(this,"UserName","").toString());
            requestParams.put("sSyu",SPUtils.get(this,"YuInfo","").toString());
            requestParams.put("sType","6");
            requestParams.put("isFull",1);
            HttpUtils.post(Constant.SCRKURL, requestParams, new TextHttpResponseHandler() {
                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                }

                @Override
                public void onStart() {
                    super.onStart();
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    handler.sendEmptyMessage(1);
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    if(responseString.contains("true")){
                        MyApp.getInstance().delete(SQLiteDbHelper.TABLE_STUDENT,
                                "time = ?", new String[]{time});
                    }else{
                    }
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    private void kpcg(List<GangPingBean> list,String ydhao, final String time){
        JSONArray array=null;
        try {
            array=new JSONArray();
            JSONObject object;
            for(int i=0;i<list.size();i++){
                object=new JSONObject();
                object.put("钢瓶号",list.get(i).getGangPingHao());
                object.put("介质",list.get(i).getInvName());
                object.put("规格",list.get(i).getcInvStd());
                object.put("物料编码",list.get(i).getcInvCode());
                object.put("充前重量","");
                object.put("充后重量","");
                array.put(object);
            }
            RequestParams requestParams=new RequestParams();
            requestParams.put("sJson",array.toString().replace("=",":"));
            requestParams.put("sFaYunDanHao",ydhao);
            requestParams.put("sStorageScanID",SPUtils.get(this,"UserName","").toString());
            requestParams.put("sSyu",SPUtils.get(this,"YuInfo","").toString());
            requestParams.put("sType",6);
            requestParams.put("sTiSongHuoDanHao","");
            HttpUtils.post(Constant.KPCGURL, requestParams, new TextHttpResponseHandler() {
                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                }

                @Override
                public void onStart() {
                    super.onStart();
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    handler.sendEmptyMessage(1);
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    if(responseString.contains("true")){
                        MyApp.getInstance().delete(SQLiteDbHelper.TABLE_STUDENT,
                                "time = ?", new String[]{time});
                    }else{
                    }
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    private void hcqr(List<GangPingBean> list,String ydhao, final String time) {
        JSONArray array = null;
        try {
            array = new JSONArray();
            JSONObject object;
            for (int i = 0; i < list.size(); i++) {
                object = new JSONObject();
                object.put("gangpinghao", list.get(i).getGangPingHao());
                object.put("isfull", list.get(i).getIsFull());
                object.put("backConfirm", list.get(i).getBackConfirm());
                array.put(object);
            }
            RequestParams requestParams = new RequestParams();
            requestParams.put("sJson", array.toString().replace("=", ":"));
            requestParams.put("yunDanHao", ydhao);
            requestParams.put("sStorageScanID", SPUtils.get(this, "UserName", "").toString());
            requestParams.put("sSyu", SPUtils.get(this, "YuInfo", "").toString());
            requestParams.put("sType", "2");
            requestParams.put("isFull", 0);
            HttpUtils.post(Constant.SCRKURL, requestParams, new TextHttpResponseHandler() {
                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                }

                @Override
                public void onStart() {
                    super.onStart();
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    handler.sendEmptyMessage(1);
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    if (responseString.contains("true")) {
                        MyApp.getInstance().delete(SQLiteDbHelper.TABLE_STUDENT,
                                "time = ?", new String[]{time});
                    } else {
                    }
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    private void firstSubmit(final List<GangPingBean> list, final String time){
        JSONArray array=null;
        try {
            array=new JSONArray();
            JSONObject object;
            for(int i=0;i<list.size();i++){
                object=new JSONObject();
                object.put("钢瓶号",list.get(i).getGangPingHao());
                object.put("介质",list.get(i).getInvName());
                object.put("规格",list.get(i).getcInvStd());
                object.put("物料编码",list.get(i).getcInvCode());
                object.put("充前重量","");
                object.put("充后重量","");
                array.put(object);
            }
            RequestParams requestParams=new RequestParams();
            requestParams.put("sJson",array.toString().replace("=",":"));
            requestParams.put("sType","33");
            requestParams.put("sStorageScanID",SPUtils.get(this,"UserName","").toString());
            requestParams.put("sSyu",SPUtils.get(this,"YuInfo","").toString());
            requestParams.put("isFull",0);
            requestParams.put("yunDanHao","");
            HttpUtils.post(Constant.SCRKURL, requestParams, new TextHttpResponseHandler() {
                @Override
                public void onStart() {
                    super.onStart();
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                }
                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    if(responseString.contains("true")){
                        secondSubmit(list,time);
                    }
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    private void secondSubmit(List<GangPingBean> list, final String time){
        JSONArray array=null;
        try {
            array=new JSONArray();
            JSONObject object;
            for(int i=0;i<list.size();i++){
                object=new JSONObject();
                object.put("钢瓶号",list.get(i).getGangPingHao());
                object.put("介质",list.get(i).getInvName());
                object.put("规格",list.get(i).getcInvStd());
                object.put("物料编码",list.get(i).getcInvCode());
                object.put("充前重量","");
                object.put("充后重量","");
                array.put(object);
            }
            RequestParams requestParams=new RequestParams();
            requestParams.put("sJson",array.toString().replace("=",":"));
            requestParams.put("sType","1");
            requestParams.put("sStorageScanID",SPUtils.get(this,"UserName","").toString());
            requestParams.put("sSyu",SPUtils.get(this,"YuInfo","").toString());
            requestParams.put("isFull",0);
            requestParams.put("yunDanHao","");
            HttpUtils.post(Constant.SCRKURL, requestParams, new TextHttpResponseHandler() {
                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

                }
                @Override
                public void onStart() {
                    super.onStart();
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    handler.sendEmptyMessage(1);
                }
                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    if(responseString.contains("true")){
                        MyApp.getInstance().delete(SQLiteDbHelper.TABLE_STUDENT,
                                "time = ?", new String[]{time});
                    }else{

                    }
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    private void scck(List<GangPingBean> list,String ydhao, final String time){
        JSONArray array=null;
        try {
            array=new JSONArray();
            JSONObject object;
            for(int i=0;i<list.size();i++){
                object=new JSONObject();
                object.put("钢瓶号",list.get(i).getGangPingHao());
                object.put("介质",list.get(i).getInvName());
                object.put("规格",list.get(i).getcInvStd());
                object.put("物料编码",list.get(i).getcInvCode());
                object.put("充前重量","");
                object.put("充后重量","");
                array.put(object);
            }
            RequestParams requestParams=new RequestParams();
            requestParams.put("sJson",array.toString().replace("=",":"));
            requestParams.put("sFaYunDanHao",ydhao);
            requestParams.put("sStorageScanID",SPUtils.get(this,"UserName","").toString());
            requestParams.put("sSyu",SPUtils.get(this,"YuInfo","").toString());
            requestParams.put("sTiSongHuoDanHao","");
            HttpUtils.post(Constant.SCCKURL, requestParams, new TextHttpResponseHandler() {
                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                }

                @Override
                public void onStart() {
                    super.onStart();
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    handler.sendEmptyMessage(1);
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    if(responseString.contains("true")){
                        MyApp.getInstance().delete(SQLiteDbHelper.TABLE_STUDENT,
                                "time = ?", new String[]{time});
                    }else{
                    }
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopService(intent);
        if(timer!=null&&cancle){
            timer.cancel();
            timer=null;
        }
    }

    public void click(View view) {
        switch (view.getId()) {
            case R.id.btn_scrk:
                startActivity(new Intent(this, SCRKActivity.class));
                break;
            case R.id.btn_scck:
                startActivity(new Intent(this, SCCKActivity.class));
                break;
            case R.id.btn_hcqr:
                startActivity(new Intent(this, HCQRActivity.class));
                break;
            case R.id.btn_ztck:
                startActivity(new Intent(this, ZTCKActivity.class));
                break;
            case R.id.btn_ztrk:
                startActivity(new Intent(this, ZTRKActivity.class));
                break;
            case R.id.btn_cgrk:
                startActivity(new Intent(this, CGRKActivity.class));
                break;
            case R.id.btn_kpcg:
                startActivity(new Intent(this, KPCGActivity.class));
                break;
            case R.id.btn_record:
                startActivity(new Intent(this, HistoryActivity.class));
                break;
        }
    }
}
